from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.utils import timezone
from django.db.models import Q
import logging

from .models import (
    JenkinsServer, Project, Environment, JenkinsJob,
    JenkinsBuild, JenkinsAudit
)
from .serializers import (
    JenkinsServerSerializer, JenkinsServerListSerializer, ProjectSerializer,
    EnvironmentSerializer, JenkinsJobSerializer, JenkinsJobListSerializer,
    JenkinsBuildSerializer, JenkinsBuildListSerializer, JenkinsAuditSerializer,
    JenkinsAuditListSerializer
)
from .jenkins_api import JenkinsAPIManager
from .jenkins_config_generator import JenkinsConfigGenerator

logger = logging.getLogger(__name__)


class JenkinsServerViewSet(viewsets.ModelViewSet):
    """Jenkins服务器管理"""
    queryset = JenkinsServer.objects.all()
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.action == 'list':
            return JenkinsServerListSerializer
        return JenkinsServerSerializer

    @action(detail=True, methods=['post'])
    def test_connection(self, request, pk=None):
        """测试Jenkins服务器连接"""
        server = self.get_object()

        try:
            # 更新状态为测试中
            server.status = 'testing'
            server.save()

            # 创建API管理器并测试连接
            api_manager = JenkinsAPIManager(
                server_url=server.url,
                username=server.username,
                api_token=server.api_token
            )

            result = api_manager.test_connection()

            # 更新服务器状态
            if result['success']:
                server.status = 'connected'
                server.last_check = timezone.now()

                # 记录审计日志
                JenkinsAudit.objects.create(
                    operation_type='jenkins_server_test',
                    user=request.user,
                    jenkins_server=server,
                    result='success',
                    details=result
                )
            else:
                server.status = 'disconnected'

                # 记录审计日志
                JenkinsAudit.objects.create(
                    operation_type='jenkins_server_test',
                    user=request.user,
                    jenkins_server=server,
                    result='failed',
                    details=result,
                    error_message=result.get('message', '')
                )

            server.save()

            return Response(result)

        except Exception as e:
            logger.error(f"测试Jenkins连接失败: {str(e)}")
            server.status = 'error'
            server.save()

            # 记录审计日志
            JenkinsAudit.objects.create(
                operation_type='jenkins_server_test',
                user=request.user,
                jenkins_server=server,
                result='failed',
                error_message=str(e)
            )

            return Response({
                'success': False,
                'message': f'连接测试失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['post'])
    def sync_jobs(self, request, pk=None):
        """同步Jenkins任务"""
        server = self.get_object()

        try:
            # 创建API管理器
            api_manager = JenkinsAPIManager(
                server_url=server.url,
                username=server.username,
                api_token=server.api_token
            )

            # 获取Jenkins任务列表
            jenkins_jobs = api_manager.get_jobs()

            synced_count = 0
            for job_data in jenkins_jobs:
                # 创建或更新Jenkins任务记录
                # 智能匹配项目和环境
                logger.info(f"开始匹配Jenkins任务: {job_data['name']}")
                project, environment = self._match_project_and_environment(job_data)
                logger.info(f"匹配结果 - 项目: {project}, 环境: {environment}")

                # 尝试匹配GitLab项目
                gitlab_project = self._match_gitlab_project(job_data)
                logger.info(f"GitLab项目匹配结果: {gitlab_project.name if gitlab_project else '未找到'}")

                # 只有匹配到项目和环境才创建任务
                if project and environment:
                    job, created = JenkinsJob.objects.update_or_create(
                        jenkins_server=server,
                        jenkins_job_name=job_data['name'],
                        defaults={
                            'name': job_data.get('displayName', job_data['name']),
                            'description': job_data.get('description', ''),
                            'job_type': self._detect_job_type(job_data),
                            'project': project,
                            'environment': environment,
                            'jenkins_job_url': job_data['url'],
                            'gitlab_project_id': gitlab_project.id if gitlab_project else None,
                            'gitlab_project_name': gitlab_project.name if gitlab_project else None,
                            'is_active': True,
                            'last_build_number': job_data.get('lastBuild', {}).get('number') if job_data.get('lastBuild') else None,
                            'last_build_status': self._get_build_status(job_data.get('lastBuild')),
                            'last_build_time': self._parse_build_time(job_data.get('lastBuild')),
                        }
                    )
                    synced_count += 1
                    logger.info(f"同步Jenkins任务成功: {job_data['name']}, GitLab关联: {gitlab_project.name if gitlab_project else '无'}")
                else:
                    # 记录未匹配的任务，供后续手动关联
                    logger.warning(f"Jenkins任务 '{job_data['name']}' 未找到匹配的GitLab项目和环境，跳过同步")

            # 更新服务器统计信息
            server.job_count = synced_count
            server.last_sync = timezone.now()
            server.save()

            # 记录审计日志
            JenkinsAudit.objects.create(
                operation_type='jenkins_job_sync',
                user=request.user,
                jenkins_server=server,
                result='success',
                details={
                    'synced_jobs': synced_count,
                    'jobs': jenkins_jobs
                }
            )

            return Response({
                'success': True,
                'message': f'成功同步 {synced_count} 个任务',
                'synced_count': synced_count
            })

        except Exception as e:
            logger.error(f"同步Jenkins任务失败: {str(e)}")

            # 记录审计日志
            JenkinsAudit.objects.create(
                operation_type='jenkins_job_sync',
                user=request.user,
                jenkins_server=server,
                result='failed',
                error_message=str(e)
            )

            return Response({
                'success': False,
                'message': f'同步任务失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def _detect_job_type(self, job_data):
        """检测Jenkins任务类型"""
        job_class = job_data.get('_class', '')
        if 'FreeStyleProject' in job_class:
            return 'freestyle'
        elif 'MavenModuleSet' in job_class:
            return 'maven'
        elif 'WorkflowJob' in job_class:
            return 'pipeline'
        else:
            return 'freestyle'  # 默认类型

    def _get_build_status(self, last_build):
        """获取最后构建状态"""
        if not last_build:
            return None

        # 从Jenkins API返回的数据中获取构建状态
        if 'result' in last_build:
            result = last_build['result']
            if result is None:
                # 如果result为null，检查是否正在构建
                return 'BUILDING' if last_build.get('building', False) else 'UNKNOWN'
            return result

        return None

    def _parse_build_time(self, last_build):
        """解析构建时间"""
        if not last_build:
            return None

        # 从Jenkins API返回的数据中获取构建时间戳
        if 'timestamp' in last_build:
            try:
                # Jenkins时间戳是毫秒，需要转换为秒
                timestamp_ms = last_build['timestamp']
                timestamp_s = timestamp_ms / 1000
                return timezone.datetime.fromtimestamp(timestamp_s, tz=timezone.get_current_timezone())
            except (ValueError, TypeError):
                pass

        return None

    def _get_build_status_display(self, status):
        """获取状态显示文本"""
        status_map = {
            'SUCCESS': '成功',
            'FAILURE': '失败',
            'UNSTABLE': '不稳定',
            'ABORTED': '已中止',
            'BUILDING': '构建中',
            'UNKNOWN': '未知'
        }
        return status_map.get(status, '未知')

    def _parse_jenkins_timestamp(self, timestamp_ms):
        """解析Jenkins时间戳（毫秒）为Django时间"""
        if not timestamp_ms:
            return None
        try:
            timestamp_s = timestamp_ms / 1000
            return timezone.datetime.fromtimestamp(timestamp_s, tz=timezone.get_current_timezone())
        except (ValueError, TypeError):
            return None

    def _parse_jenkins_end_time(self, start_timestamp_ms, duration_ms):
        """计算结束时间"""
        if not start_timestamp_ms or not duration_ms:
            return None
        try:
            end_timestamp_ms = start_timestamp_ms + duration_ms
            timestamp_s = end_timestamp_ms / 1000
            return timezone.datetime.fromtimestamp(timestamp_s, tz=timezone.get_current_timezone())
        except (ValueError, TypeError):
            return None

    def _match_gitlab_project(self, job_data):
        """匹配GitLab项目"""
        from gitlab_integration.models import GitLabProject

        job_name = job_data['name'].lower()

        # 1. 精确匹配项目名称或路径
        gitlab_project = GitLabProject.objects.filter(
            Q(name__iexact=job_name) |
            Q(path__iexact=job_name)
        ).first()

        if gitlab_project:
            return gitlab_project

        # 2. 模糊匹配项目名称
        gitlab_project = GitLabProject.objects.filter(
            Q(name__icontains=job_name) |
            Q(path__icontains=job_name)
        ).first()

        if gitlab_project:
            return gitlab_project

        # 3. 根据任务名称的前缀匹配
        parts = job_name.replace('-', '_').split('_')
        if len(parts) >= 1:
            potential_project_name = parts[0]
            gitlab_project = GitLabProject.objects.filter(
                Q(name__icontains=potential_project_name) |
                Q(path__icontains=potential_project_name)
            ).first()

            if gitlab_project:
                return gitlab_project

        return None

    def _match_project_and_environment(self, job_data):
        """智能匹配项目和环境 - 优先从GitLab项目关联"""
        job_name = job_data['name'].lower()

        # 1. 首先尝试从GitLab项目中匹配（根据项目名称）
        from gitlab_integration.models import GitLabProject

        # 查找GitLab中同名的项目
        gitlab_projects = GitLabProject.objects.filter(
            Q(name__iexact=job_name) |
            Q(path__iexact=job_name) |
            Q(name__icontains=job_name)
        ).filter(
            project__isnull=False,  # 确保已关联项目
            environment__isnull=False  # 确保已关联环境
        )

        if gitlab_projects.exists():
            gitlab_project = gitlab_projects.first()
            # 在Jenkins的Project和Environment表中创建对应记录
            jenkins_project, _ = Project.objects.get_or_create(
                code=gitlab_project.project.code,
                defaults={
                    'name': gitlab_project.project.name,
                    'description': gitlab_project.project.description,
                    'is_active': gitlab_project.project.is_active
                }
            )
            jenkins_environment, _ = Environment.objects.get_or_create(
                code=gitlab_project.environment.code,
                defaults={
                    'name': gitlab_project.environment.name,
                    'description': gitlab_project.environment.description,
                    'is_active': gitlab_project.environment.is_active
                }
            )
            return jenkins_project, jenkins_environment

        # 2. 如果没有找到完全匹配的GitLab项目，尝试模糊匹配
        # 常见的命名模式：项目名-环境-功能 或 项目名_环境_功能
        parts = job_name.replace('-', '_').split('_')

        if len(parts) >= 1:
            potential_project_name = parts[0]

            # 在GitLab项目中查找匹配的项目名
            gitlab_projects = GitLabProject.objects.filter(
                Q(name__icontains=potential_project_name) |
                Q(path__icontains=potential_project_name)
            ).filter(
                project__isnull=False,
                environment__isnull=False
            )

            if gitlab_projects.exists():
                gitlab_project = gitlab_projects.first()

                # 如果任务名包含环境关键词，尝试匹配更精确的环境
                if len(parts) > 1:
                    env_keywords = {
                        'dev': ['dev', 'develop', 'development'],
                        'test': ['test', 'testing', 'qa'],
                        'uat': ['uat', 'staging', 'pre', 'preprod'],
                        'prod': ['prod', 'production', 'live']
                    }

                    for part in parts[1:]:
                        for env_code, keywords in env_keywords.items():
                            if any(keyword in part for keyword in keywords):
                                # 查找匹配的环境
                                from gitlab_integration.models import Environment as GitLabEnvironment
                                gitlab_environments = GitLabEnvironment.objects.filter(
                                    Q(code__icontains=env_code) |
                                    Q(name__icontains=env_code)
                                )
                                if gitlab_environments.exists():
                                    gitlab_env = gitlab_environments.first()
                                    # 在Jenkins表中创建对应记录
                                    jenkins_project, _ = Project.objects.get_or_create(
                                        code=gitlab_project.project.code,
                                        defaults={
                                            'name': gitlab_project.project.name,
                                            'description': gitlab_project.project.description,
                                            'is_active': gitlab_project.project.is_active
                                        }
                                    )
                                    jenkins_environment, _ = Environment.objects.get_or_create(
                                        code=gitlab_env.code,
                                        defaults={
                                            'name': gitlab_env.name,
                                            'description': gitlab_env.description,
                                            'is_active': gitlab_env.is_active
                                        }
                                    )
                                    return jenkins_project, jenkins_environment

                # 如果没有找到特定环境，使用GitLab项目的默认环境
                jenkins_project, _ = Project.objects.get_or_create(
                    code=gitlab_project.project.code,
                    defaults={
                        'name': gitlab_project.project.name,
                        'description': gitlab_project.project.description,
                        'is_active': gitlab_project.project.is_active
                    }
                )
                jenkins_environment, _ = Environment.objects.get_or_create(
                    code=gitlab_project.environment.code,
                    defaults={
                        'name': gitlab_project.environment.name,
                        'description': gitlab_project.environment.description,
                        'is_active': gitlab_project.environment.is_active
                    }
                )
                return jenkins_project, jenkins_environment

        # 3. 如果都没有匹配到，返回None让用户手动关联
        return None, None

    @action(detail=False, methods=['post'])
    def test_all_connections(self, request):
        """测试所有服务器连接"""
        servers = JenkinsServer.objects.filter(is_active=True)
        results = []

        for server in servers:
            try:
                api_manager = JenkinsAPIManager(
                    server_url=server.url,
                    username=server.username,
                    api_token=server.api_token
                )

                result = api_manager.test_connection()

                # 更新服务器状态
                if result['success']:
                    server.status = 'connected'
                else:
                    server.status = 'disconnected'

                server.last_check = timezone.now()
                server.save()

                results.append({
                    'server_id': server.id,
                    'server_name': server.name,
                    'success': result['success'],
                    'message': result['message']
                })

            except Exception as e:
                server.status = 'error'
                server.save()

                results.append({
                    'server_id': server.id,
                    'server_name': server.name,
                    'success': False,
                    'message': str(e)
                })

        return Response({
            'success': True,
            'results': results
        })

    def perform_create(self, serializer):
        """创建服务器时记录审计日志"""
        server = serializer.save()

        JenkinsAudit.objects.create(
            operation_type='jenkins_server_create',
            user=self.request.user,
            jenkins_server=server,
            result='success',
            details={
                'server_name': server.name,
                'server_url': server.url
            }
        )

    def perform_update(self, serializer):
        """更新服务器时记录审计日志"""
        server = serializer.save()

        JenkinsAudit.objects.create(
            operation_type='jenkins_server_update',
            user=self.request.user,
            jenkins_server=server,
            result='success',
            details={
                'server_name': server.name,
                'server_url': server.url
            }
        )

    def perform_destroy(self, instance):
        """删除服务器时记录审计日志"""
        JenkinsAudit.objects.create(
            operation_type='jenkins_server_delete',
            user=self.request.user,
            jenkins_server=instance,
            result='success',
            details={
                'server_name': instance.name,
                'server_url': instance.url
            }
        )

        instance.delete()


class ProjectViewSet(viewsets.ModelViewSet):
    """项目管理"""
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
    permission_classes = [IsAuthenticated]


class EnvironmentViewSet(viewsets.ModelViewSet):
    """环境管理"""
    queryset = Environment.objects.all()
    serializer_class = EnvironmentSerializer
    permission_classes = [IsAuthenticated]


class JenkinsJobViewSet(viewsets.ModelViewSet):
    """Jenkins任务管理"""
    queryset = JenkinsJob.objects.all()
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.action == 'list':
            return JenkinsJobListSerializer
        return JenkinsJobSerializer

    def get_queryset(self):
        """支持过滤查询"""
        queryset = JenkinsJob.objects.all()

        # 项目过滤
        project_id = self.request.query_params.get('project_id')
        if project_id:
            queryset = queryset.filter(project_id=project_id)

        # 环境过滤
        environment_id = self.request.query_params.get('environment_id')
        if environment_id:
            queryset = queryset.filter(environment_id=environment_id)

        # 服务器过滤
        jenkins_server_id = self.request.query_params.get('jenkins_server_id')
        if jenkins_server_id:
            queryset = queryset.filter(jenkins_server_id=jenkins_server_id)

        # 任务类型过滤
        job_type = self.request.query_params.get('job_type')
        if job_type:
            queryset = queryset.filter(job_type=job_type)

        # 搜索
        search = self.request.query_params.get('search')
        if search:
            queryset = queryset.filter(
                Q(name__icontains=search) |
                Q(description__icontains=search) |
                Q(jenkins_job_name__icontains=search)
            )

        return queryset.order_by('-created_at')

    @action(detail=True, methods=['post'])
    def trigger_build(self, request, pk=None):
        """触发构建"""
        job = self.get_object()

        try:
            # 创建API管理器
            api_manager = JenkinsAPIManager(
                server_url=job.jenkins_server.url,
                username=job.jenkins_server.username,
                api_token=job.jenkins_server.api_token
            )

            # 获取构建参数
            parameters = request.data.get('parameters', {})

            # 触发构建
            result = api_manager.trigger_build(job.jenkins_job_name, parameters)

            # 如果构建触发成功，获取最新构建信息并更新任务
            if result['success']:
                # 等待一下让Jenkins处理构建请求
                import time
                time.sleep(2)

                # 获取最新的构建信息
                job_details = api_manager.get_job_details(job.jenkins_job_name)
                if job_details and 'nextBuildNumber' in job_details:
                    # 最新构建号是nextBuildNumber - 1
                    latest_build_number = job_details['nextBuildNumber'] - 1
                    job.last_build_number = latest_build_number
                    job.last_build_status = 'BUILDING'
                    job.last_build_time = timezone.now()
                    job.save()

                    # 更新返回结果中的构建号
                    result['build_number'] = latest_build_number

            # 记录审计日志
            JenkinsAudit.objects.create(
                operation_type='jenkins_build_trigger',
                user=request.user,
                project=job.project,
                environment=job.environment,
                jenkins_server=job.jenkins_server,
                jenkins_job=job,
                result='success' if result['success'] else 'failed',
                details={
                    'job_name': job.jenkins_job_name,
                    'parameters': parameters,
                    'result': result
                },
                error_message=result.get('message', '') if not result['success'] else None
            )

            return Response(result)

        except Exception as e:
            logger.error(f"触发Jenkins构建失败: {str(e)}")

            # 记录审计日志
            JenkinsAudit.objects.create(
                operation_type='jenkins_build_trigger',
                user=request.user,
                project=job.project,
                environment=job.environment,
                jenkins_server=job.jenkins_server,
                jenkins_job=job,
                result='failed',
                error_message=str(e)
            )

            return Response({
                'success': False,
                'message': f'触发构建失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['get'])
    def builds(self, request, pk=None):
        """获取任务的构建记录（直接从Jenkins API获取）"""
        job = self.get_object()

        try:
            # 创建API管理器
            api_manager = JenkinsAPIManager(
                server_url=job.jenkins_server.url,
                username=job.jenkins_server.username,
                api_token=job.jenkins_server.api_token
            )

            # 从Jenkins API获取构建历史
            builds_result = api_manager.get_job_builds(job.jenkins_job_name)

            if builds_result['success']:
                builds_data = []
                for build_info in builds_result['builds']:
                    build_status = build_info.get('result', 'BUILDING' if build_info.get('building') else 'UNKNOWN')
                    # 状态显示映射
                    status_display_map = {
                        'SUCCESS': '成功',
                        'FAILURE': '失败',
                        'UNSTABLE': '不稳定',
                        'ABORTED': '已中止',
                        'BUILDING': '构建中',
                        'UNKNOWN': '未知'
                    }

                    builds_data.append({
                        'id': build_info['number'],  # 使用构建号作为ID
                        'job_name': job.name,
                        'project_name': job.project.name if job.project else '',
                        'environment_name': job.environment.name if job.environment else '',
                        'build_number': build_info['number'],
                        'status': build_status,
                        'status_display': status_display_map.get(build_status, '未知'),
                        'duration': build_info.get('duration', 0),
                        'start_time': timezone.datetime.fromtimestamp(build_info.get('timestamp', 0) / 1000, tz=timezone.get_current_timezone()) if build_info.get('timestamp') else None,
                        'end_time': timezone.datetime.fromtimestamp((build_info.get('timestamp', 0) + build_info.get('duration', 0)) / 1000, tz=timezone.get_current_timezone()) if build_info.get('timestamp') and build_info.get('duration') else None,
                        'triggered_by': 'admin',  # Jenkins API中可能需要额外调用获取
                        'git_commit': None,
                        'git_branch': None,
                        'created_at': timezone.datetime.fromtimestamp(build_info.get('timestamp', 0) / 1000, tz=timezone.get_current_timezone()) if build_info.get('timestamp') else None
                    })

                # 按构建号倒序排列
                builds_data.sort(key=lambda x: x['build_number'], reverse=True)

                return Response({
                    'results': builds_data,
                    'total': len(builds_data),
                    'page': 1,
                    'page_size': len(builds_data),
                    'total_pages': 1
                })
            else:
                return Response({
                    'results': [],
                    'total': 0,
                    'page': 1,
                    'page_size': 20,
                    'total_pages': 0,
                    'error': builds_result['message']
                }, status=400)

        except Exception as e:
            logger.error(f"获取构建历史失败: {str(e)}")
            return Response({
                'results': [],
                'total': 0,
                'page': 1,
                'page_size': 20,
                'total_pages': 0,
                'error': f'获取构建历史失败: {str(e)}'
            }, status=500)

    @action(detail=True, methods=['get'])
    def sync_builds(self, request, pk=None):
        """同步任务的构建历史"""
        job = self.get_object()

        try:
            # 创建API管理器
            api_manager = JenkinsAPIManager(
                server_url=job.jenkins_server.url,
                username=job.jenkins_server.username,
                api_token=job.jenkins_server.api_token
            )

            # 获取任务详情
            job_details = api_manager.get_job_details(job.jenkins_job_name)
            if not job_details:
                return Response({
                    'success': False,
                    'message': '无法获取Jenkins任务详情'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 同步构建记录
            builds = job_details.get('builds', [])
            synced_count = 0

            for build_info in builds[:50]:  # 限制同步最近50个构建
                build_number = build_info.get('number')
                if not build_number:
                    continue

                # 检查是否已存在
                if JenkinsBuild.objects.filter(job=job, build_number=build_number).exists():
                    continue

                # 获取详细构建信息
                build_details = api_manager.get_build_info(job.jenkins_job_name, build_number)
                if not build_details:
                    continue

                # 创建构建记录
                JenkinsBuild.objects.create(
                    job=job,
                    build_number=build_number,
                    status=build_details.get('result', 'BUILDING'),
                    duration=build_details.get('duration'),
                    start_time=timezone.datetime.fromtimestamp(
                        build_details.get('timestamp', 0) / 1000,
                        tz=timezone.get_current_timezone()
                    ),
                    end_time=timezone.datetime.fromtimestamp(
                        (build_details.get('timestamp', 0) + build_details.get('duration', 0)) / 1000,
                        tz=timezone.get_current_timezone()
                    ) if build_details.get('duration') else None,
                    parameters=build_details.get('actions', [{}])[0].get('parameters', {}),
                    triggered_by=build_details.get('actions', [{}])[0].get('causes', [{}])[0].get('userName', ''),
                    jenkins_build_url=build_details.get('url', '')
                )

                synced_count += 1

            return Response({
                'success': True,
                'message': f'成功同步 {synced_count} 个构建记录',
                'synced_count': synced_count
            })

        except Exception as e:
            logger.error(f"同步Jenkins构建历史失败: {str(e)}")
            return Response({
                'success': False,
                'message': f'同步构建历史失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def perform_create(self, serializer):
        """创建任务时在Jenkins中实际创建任务并记录审计日志"""
        # 设置jenkins_job_name如果没有提供
        if not serializer.validated_data.get('jenkins_job_name'):
            serializer.validated_data['jenkins_job_name'] = serializer.validated_data['name']

        job = serializer.save()

        # 在Jenkins中创建实际任务
        try:
            result = self._create_jenkins_job(job)
            if not result['success']:
                logger.error(f"在Jenkins中创建任务失败: {result['message']}")
                # 记录失败的审计日志
                JenkinsAudit.objects.create(
                    operation_type='jenkins_job_create',
                    user=self.request.user,
                    project=job.project,
                    environment=job.environment,
                    jenkins_server=job.jenkins_server,
                    jenkins_job=job,
                    result='failed',
                    error_message=result['message']
                )
                return
        except Exception as e:
            logger.error(f"在Jenkins中创建任务异常: {str(e)}")
            # 记录异常的审计日志
            JenkinsAudit.objects.create(
                operation_type='jenkins_job_create',
                user=self.request.user,
                project=job.project,
                environment=job.environment,
                jenkins_server=job.jenkins_server,
                jenkins_job=job,
                result='failed',
                error_message=str(e)
            )
            return

        # 记录成功的审计日志
        JenkinsAudit.objects.create(
            operation_type='jenkins_job_create',
            user=self.request.user,
            project=job.project,
            environment=job.environment,
            jenkins_server=job.jenkins_server,
            jenkins_job=job,
            result='success',
            details={
                'job_name': job.name,
                'jenkins_job_name': job.jenkins_job_name,
                'job_type': job.job_type
            }
        )

    def _create_jenkins_job(self, job):
        """在Jenkins中创建实际任务"""
        try:
            # 创建API管理器
            api_manager = JenkinsAPIManager(
                server_url=job.jenkins_server.url,
                username=job.jenkins_server.username,
                api_token=job.jenkins_server.api_token
            )

            # 根据任务类型生成配置XML
            config_xml = self._generate_job_config_xml(job)

            # 保存生成的XML配置
            job.config_xml = config_xml
            job.save()

            # 在Jenkins中创建任务
            result = api_manager.create_job(job.jenkins_job_name, config_xml)

            if result['success']:
                # 更新任务URL
                job.jenkins_job_url = f"{job.jenkins_server.url}/job/{job.jenkins_job_name}/"
                job.save()
                logger.info(f"在Jenkins中成功创建任务: {job.jenkins_job_name}")
                return {'success': True, 'message': '任务创建成功'}
            else:
                logger.error(f"在Jenkins中创建任务失败: {result['message']}")
                return {'success': False, 'message': result['message']}

        except Exception as e:
            logger.error(f"创建Jenkins任务异常: {str(e)}")
            return {'success': False, 'message': str(e)}

    def _generate_job_config_xml(self, job):
        """根据任务类型生成Jenkins配置XML"""
        generator = JenkinsConfigGenerator()
        return generator.generate_job_config_xml(job)


        """生成Freestyle项目配置XML"""
        git_url = ""
        if job.gitlab_project_id:
            # 这里可以根据GitLab项目ID获取仓库URL
            # 暂时使用占位符
            git_url = f"http://gitlab.example.com/project/{job.gitlab_project_id}.git"

        config_xml = f"""<?xml version='1.1' encoding='UTF-8'?>
<project>
  <actions/>
  <description>{job.description or ''}</description>
  <keepDependencies>false</keepDependencies>
  <properties/>
  <scm class="hudson.plugins.git.GitSCM" plugin="git@4.8.3">
    <configVersion>2</configVersion>
    <userRemoteConfigs>
      <hudson.plugins.git.UserRemoteConfig>
        <url>{git_url}</url>
      </hudson.plugins.git.UserRemoteConfig>
    </userRemoteConfigs>
    <branches>
      <hudson.plugins.git.BranchSpec>
        <name>*/main</name>
      </hudson.plugins.git.BranchSpec>
    </branches>
    <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
    <submoduleCfg class="list"/>
    <extensions/>
  </scm>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command>echo "构建开始"
echo "项目: {job.project.name}"
echo "环境: {job.environment.name}"
echo "构建完成"</command>
    </hudson.tasks.Shell>
  </builders>
  <publishers/>
  <buildWrappers/>
</project>"""
        return config_xml

    def _generate_maven_config(self, job):
        """生成Maven项目配置XML"""
        # 简化的Maven配置
        return self._generate_freestyle_config(job).replace(
            '<hudson.tasks.Shell>',
            '<hudson.tasks.Maven>'
        ).replace(
            '</hudson.tasks.Shell>',
            '</hudson.tasks.Maven>'
        ).replace(
            '<command>',
            '<targets>clean compile package</targets><mavenName>Maven</mavenName><pom>pom.xml</pom><properties>'
        ).replace(
            '</command>',
            '</properties>'
        )

    def _generate_pipeline_config(self, job):
        """生成Pipeline项目配置XML"""
        pipeline_script = f"""pipeline {{
    agent any

    stages {{
        stage('Checkout') {{
            steps {{
                echo '检出代码'
                // git branch: 'main', url: 'your-git-url'
            }}
        }}

        stage('Build') {{
            steps {{
                echo '构建项目: {job.project.name}'
                echo '环境: {job.environment.name}'
            }}
        }}

        stage('Test') {{
            steps {{
                echo '运行测试'
            }}
        }}

        stage('Deploy') {{
            steps {{
                echo '部署到 {job.environment.name} 环境'
            }}
        }}
    }}

    post {{
        always {{
            echo '构建完成'
        }}
    }}
}}"""

        config_xml = f"""<?xml version='1.1' encoding='UTF-8'?>
<flow-definition plugin="workflow-job@2.40">
  <actions/>
  <description>{job.description or ''}</description>
  <keepDependencies>false</keepDependencies>
  <properties/>
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.92">
    <script>{pipeline_script}</script>
    <sandbox>true</sandbox>
  </definition>
  <triggers/>
  <disabled>false</disabled>
</flow-definition>"""
        return config_xml

    @action(detail=True, methods=['get'], url_path='console/(?P<build_number>[^/.]+)')
    def get_build_console(self, request, pk=None, build_number=None):
        """获取构建控制台日志"""
        job = self.get_object()

        try:
            # 创建API管理器
            api_manager = JenkinsAPIManager(
                server_url=job.jenkins_server.url,
                username=job.jenkins_server.username,
                api_token=job.jenkins_server.api_token
            )

            # 获取构建控制台日志
            console_result = api_manager.get_build_console_output(job.jenkins_job_name, int(build_number))

            if console_result['success']:
                return Response({
                    'success': True,
                    'console_output': console_result['console_output'],
                    'status': console_result.get('status', 'RUNNING'),
                    'duration': console_result.get('duration', 0),
                    'build_number': build_number
                })
            else:
                return Response({
                    'success': False,
                    'message': console_result['message'],
                    'console_output': '',
                    'status': 'UNKNOWN'
                }, status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            logger.error(f"获取构建控制台日志失败: {str(e)}")
            return Response({
                'success': False,
                'message': f'获取构建控制台日志失败: {str(e)}',
                'console_output': '',
                'status': 'ERROR'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class JenkinsBuildViewSet(viewsets.ModelViewSet):
    """Jenkins构建记录管理"""
    queryset = JenkinsBuild.objects.all()
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.action == 'list':
            return JenkinsBuildListSerializer
        return JenkinsBuildSerializer

    def get_queryset(self):
        """支持过滤查询"""
        queryset = JenkinsBuild.objects.all()

        # 任务过滤
        job_id = self.request.query_params.get('job_id')
        if job_id:
            queryset = queryset.filter(job_id=job_id)

        # 项目过滤
        project_id = self.request.query_params.get('project_id')
        if project_id:
            queryset = queryset.filter(job__project_id=project_id)

        # 环境过滤
        environment_id = self.request.query_params.get('environment_id')
        if environment_id:
            queryset = queryset.filter(job__environment_id=environment_id)

        # 状态过滤
        status_filter = self.request.query_params.get('status')
        if status_filter:
            queryset = queryset.filter(status=status_filter)

        return queryset.order_by('-build_number')

    @action(detail=True, methods=['get'])
    def console_output(self, request, pk=None):
        """获取构建控制台输出"""
        build = self.get_object()

        try:
            # 如果已有控制台输出，直接返回
            if build.console_output:
                return Response({
                    'success': True,
                    'console_output': build.console_output
                })

            # 否则从Jenkins获取
            api_manager = JenkinsAPIManager(
                server_url=build.job.jenkins_server.url,
                username=build.job.jenkins_server.username,
                api_token=build.job.jenkins_server.api_token
            )

            console_output = api_manager.get_build_console_output(
                build.job.jenkins_job_name,
                build.build_number
            )

            if console_output:
                # 保存到数据库
                build.console_output = console_output
                build.save()

                return Response({
                    'success': True,
                    'console_output': console_output
                })
            else:
                return Response({
                    'success': False,
                    'message': '无法获取控制台输出'
                }, status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            logger.error(f"获取Jenkins构建日志失败: {str(e)}")
            return Response({
                'success': False,
                'message': f'获取构建日志失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['post'])
    def abort(self, request, pk=None):
        """中止构建"""
        build = self.get_object()

        try:
            api_manager = JenkinsAPIManager(
                server_url=build.job.jenkins_server.url,
                username=build.job.jenkins_server.username,
                api_token=build.job.jenkins_server.api_token
            )

            result = api_manager.abort_build(
                build.job.jenkins_job_name,
                build.build_number
            )

            if result['success']:
                # 更新构建状态
                build.status = 'ABORTED'
                build.save()

            # 记录审计日志
            JenkinsAudit.objects.create(
                operation_type='jenkins_build_abort',
                user=request.user,
                project=build.job.project,
                environment=build.job.environment,
                jenkins_server=build.job.jenkins_server,
                jenkins_job=build.job,
                result='success' if result['success'] else 'failed',
                details={
                    'build_number': build.build_number,
                    'result': result
                },
                error_message=result.get('message', '') if not result['success'] else None
            )

            return Response(result)

        except Exception as e:
            logger.error(f"中止Jenkins构建失败: {str(e)}")

            # 记录审计日志
            JenkinsAudit.objects.create(
                operation_type='jenkins_build_abort',
                user=request.user,
                project=build.job.project,
                environment=build.job.environment,
                jenkins_server=build.job.jenkins_server,
                jenkins_job=build.job,
                result='failed',
                error_message=str(e)
            )

            return Response({
                'success': False,
                'message': f'中止构建失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class JenkinsAuditViewSet(viewsets.ReadOnlyModelViewSet):
    """Jenkins操作审计"""
    queryset = JenkinsAudit.objects.all()
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.action == 'list':
            return JenkinsAuditListSerializer
        return JenkinsAuditSerializer

    def get_queryset(self):
        """支持过滤查询"""
        queryset = JenkinsAudit.objects.all()

        # 操作类型过滤
        operation_type = self.request.query_params.get('operation_type')
        if operation_type:
            queryset = queryset.filter(operation_type=operation_type)

        # 用户过滤
        user_id = self.request.query_params.get('user_id')
        if user_id:
            queryset = queryset.filter(user_id=user_id)

        # 项目过滤
        project_id = self.request.query_params.get('project_id')
        if project_id:
            queryset = queryset.filter(project_id=project_id)

        # 环境过滤
        environment_id = self.request.query_params.get('environment_id')
        if environment_id:
            queryset = queryset.filter(environment_id=environment_id)

        # 结果过滤
        result = self.request.query_params.get('result')
        if result:
            queryset = queryset.filter(result=result)

        # 时间范围过滤
        start_date = self.request.query_params.get('start_date')
        end_date = self.request.query_params.get('end_date')
        if start_date:
            queryset = queryset.filter(created_at__gte=start_date)
        if end_date:
            queryset = queryset.filter(created_at__lte=end_date)

        return queryset.order_by('-created_at')
